import time
from chaojiying import *
import requests
import re
# from get_code import *


session = requests.Session()
class AccountantSpiser(object):
    def __init__(self):
        #查询地址链接
        self.add_utl = 'http://kzp.mof.gov.cn/cjcx/1_b4036a022596202.jsp'
        #查询信息链接
        self.url = 'http://kzp.mof.gov.cn/cjcx/2_b4036a022596202.jsp'
        # self.url_two = 'http://kzp.mof.gov.cn/counter/count.jsp?c_id=19'
        self.headers = {
            'Cookie': 'JSESSIONID=A650CC1B6FB754230475FE1E91E1BD93',
            'Host': 'kzp.mof.gov.cn',
            'Referer': 'http://kzp.mof.gov.cn/cjcx/1_b4036a022596202.jsp',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
        }
        self.add_dict = dict()
        self.pattern = '<option value="(\d+)">(.*?)</option>'


    #获取每个城市对应的编号
    def get_address(self):
        response = session.get(url=self.add_utl,headers=self.headers).text
        result = re.findall(self.pattern,response)
        for i in result:
            self.add_dict[i[1]] = i[0]
        # print(self.add_dict)


    def parse_html(self,add,id,name,code):
        data = {
            'province': self.add_dict[add],
            'sfzh': id,
            'xm': name,
            'atch': code
        }

        response = session.post(url=self.url,data=data,headers=self.headers).text
        print(response)

        # response1 = session.get(url=self.url_two,headers=self.headers).text
        # print(response1)

    def getCode(self):
        timestamp = int(time.time() * 100)
        url = 'http://kzp.mof.gov.cn/cjcx/img.jsp?timestamp={}'.format(timestamp)
        response = session.get(url=url, headers=self.headers)

        with open('code.jpg', 'wb') as f:
            f.write(response.content)

        chaojiying_client = Chaojiying_Client('username', 'password', '96001')
        im = open('code.jpg', 'rb').read()
        # print(chaojiying_client.PostPic(im, 1902)['pic_str'])

        return chaojiying_client.PostPic(im, 1902)['pic_str']


    def run(self):
        self.get_address()
        code = self.getCode()
        # add = input('请输入你要查询的城市：')
        add = '天津'
        id = '身份证号'
        name = '姓名'
        self.parse_html(add,id,name,code)


if __name__ == '__main__':
    spider = AccountantSpiser()
    spider.run()





